package com.chushouya.order.service.api.impl;

import com.chushouya.common.support.Contexts;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Beans;
import com.general.framework.core.lang.Check;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.chushouya.order.constants.BizTypeEnum;
import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.constants.UserOrderActionEnum;
import com.chushouya.order.dao.entity.OrderClothesProductEntity;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderAddressEntity;
import com.chushouya.order.dao.repository.OrderClothesProductRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dao.repository.OrderAddressRepository;
import com.chushouya.order.dto.admin.order.OrderQuery;
import com.chushouya.order.dto.admin.orderclothesproduct.OrderClothesProductQuery;
import com.chushouya.order.dto.api.order.OrderAddressApiDTO;
import com.chushouya.order.dto.api.order.OrderCancelApiDTO;
import com.chushouya.order.dto.api.orderclothesproduct.OrderClothesApiDTO;
import com.chushouya.order.dto.api.orderclothesproduct.OrderClothesListApiDTO;
import com.chushouya.order.dto.api.orderclothesproduct.OrderClothesProductApiDTO;
import com.chushouya.order.service.api.OrderClothesApiService;
import com.chushouya.order.service.api.UserOrderActionCtrlService;
import com.chushouya.order.service.common.CommonOrderActionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 旧衣订单API服务实现
 */
@Service
@Slf4j
public class OrderClothesApiServiceImpl implements OrderClothesApiService {

    @Resource
    private OrderClothesProductRepository orderClothesProductRepository;

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderAddressRepository orderAddressRepository;

    @Resource
    private UserOrderActionCtrlService userOrderActionCtrlService;

    @Resource
    private CommonOrderActionService commonOrderActionService;

    @Override
    public PageResult<OrderClothesListApiDTO> getOrderList(OrderClothesProductQuery query) {
        Long userId = Contexts.getUserContext().getUserId();
        
        // 构建查询条件
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setUserId(userId);
        orderQuery.setBizType(BizTypeEnum.JIUYI.value());
        // 查询订单列表
        PageResult<OrderEntity> orderPage = orderRepository.selectPageResult(orderQuery);
        return PageResult.of(orderPage,OrderClothesListApiDTO.class);
    }

    @Override
    public OrderClothesApiDTO getOrderDetail(String orderNo) {
        OrderEntity orderEntity = getOrderByNo(orderNo);

        final Long orderId = orderEntity.getOrderId();
        OrderClothesApiDTO dto = Beans.copy(orderEntity, OrderClothesApiDTO.class);
        dto.setOrderAddress(this.orderAddress(orderId));
        dto.setOrderClothesProduct(this.orderProduct(orderId));
        
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(OrderCancelApiDTO dto) {
        final String orderNo = dto.getOrderNo();
        OrderEntity orderEntity = getOrderByNo(orderNo);

        userOrderActionCtrlService.actionExecuteCheck(UserOrderActionEnum.CANCEL,orderEntity);
        final String msg = Strings.format("用户取消订单,订单号:{} {}", orderEntity.getOrderNo(),Strings.defaultString(dto.getRemark()));
        commonOrderActionService.closeOrder(orderEntity,msg,OrderStatusEnum.CANCELLED.value());


        
        log.info("取消旧衣订单成功，订单号：{}", orderNo);
    }

    /**
     * 根据订单号查询订单
     */
    private OrderEntity getOrderByNo(String orderNo) {
        if (Strings.isBlank(orderNo)) {
            throw Ex.business("订单号不能为空");
        }
        OrderQuery query = new OrderQuery();
        query.setOrderNo(orderNo);
        query.setBizType(BizTypeEnum.JIUYI.value()); // 旧衣订单类型
        
        OrderEntity orderEntity = orderRepository.selectOne(query);
        Check.notNull(orderEntity, "订单不存在");
        
        // 验证订单归属
        Long userId = Contexts.getUserContext().getUserId();
        if (!Objects.equals(orderEntity.getUserId(), userId)) {
            throw Ex.business("无权限访问该订单");
        }
        
        return orderEntity;
    }

    /**
     * 获取订单商品信息
     */
    private OrderClothesProductApiDTO orderProduct(Long orderId) {

        OrderClothesProductEntity orderProductEntity = orderClothesProductRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderProductEntity)) {
            throw Ex.business("订单商品信息不存在");
        }
        OrderClothesProductApiDTO orderProductDTO = Beans.copy(orderProductEntity, OrderClothesProductApiDTO.class);
        return orderProductDTO;
    }

    /**
     * 订单地址信息
     */
    private OrderAddressApiDTO orderAddress(Long orderId) {

        OrderAddressEntity
                orderAddressEntity = orderAddressRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderAddressEntity)) {
            throw Ex.business("订单地址信息不存在");
        }
        return Beans.copy(orderAddressEntity, OrderAddressApiDTO.class);
    }

}
